<template>
  <div class="mod-prod">
    <avue-crud
    v-if="condition"
      ref="crudRef"
      :page="page"
      :data="dataList"
      :table-loading="dataListLoading"
      :permission="permission"
      :option="tableOption"
      @search-change="onSearch"
      @selection-change="selectionChange"
      @on-load="getDataList"
    >
      <template #menu-left>
        <el-button
          v-if="isAuth('shop:pickAddr:save')"
          type="primary"
          icon="el-icon-plus"
          @click.stop="onAddOrUpdate()"
        >
          新增
        </el-button>

        <el-button
          v-if="isAuth('shop:pickAddr:delete')"
          type="danger"
          :disabled="dataListSelections.length <= 0"
          @click="onDelete()"
        >
          批量删除
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-download"
          @click="handleOutSku()"
        >
          导出SKU
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="handleImport()"
        >
          导入
        </el-button>
      </template>

<!--      <template #status="scope">-->
<!--        <el-tag v-if="scope.row.status === 1">-->
<!--          上架-->
<!--        </el-tag>-->
<!--        <el-tag v-else>-->
<!--          未上架-->
<!--        </el-tag>-->
<!--      </template>-->

      <template #status="scope">
<!--        <el-switch v-model="scope.row.status" :active-value="0" :inactive-value="1" @change="tableOption.methods.switChange(scope.row)"></el-switch>-->

        <el-switch
          v-model="scope.row.status"
          :active-value="1"
          :inactive-value="0"
          @change="switChange(scope.row)"
        ></el-switch>
      </template>



      <template #menu="scope">

        <el-button
          v-if="isAuth('prod:prod:update') && checkTop(scope.row.softNum)"
          type="primary"
          icon="el-icon-bottom"
          @click="onTopOrUpdate(scope.row.prodId,0)"
        >
          取消
        </el-button>
        <el-button
          v-if="isAuth('prod:prod:update') && !checkTop(scope.row.softNum)"
          type="primary"
          icon="el-icon-top"
          @click="onTopOrUpdate(scope.row.prodId,99999)"
        >
          置顶
        </el-button>
        <el-button
          v-if="isAuth('prod:prod:update')"
          type="primary"
          icon="el-icon-edit"
          @click="onAddOrUpdate(scope.row.prodId)"
        >
          修改
        </el-button>
        <el-button
          v-if="isAuth('prod:prod:delete')"
          type="danger"
          icon="el-icon-delete"
          @click="onDelete(scope.row.prodId)"
        >
          删除
        </el-button>
        <!-- <el-button
          v-if="isAuth('prod:prod:delete')"
          type="danger"
          icon="el-icon-delete"
          @click="setSoft(scope.row)"
        >
          排序
        </el-button> -->


<!--        <div v-if="searchParams.tagId||searchParams.categoryId">排序值：</div>-->
<!--        <el-input style="width: 100px;" v-if="searchParams.tagId" v-model="scope.row.num" @keyup.enter.native="setSoft(scope.row,scope.row.num)">-->

<!--        </el-input>-->
<!--        <el-input v-if="searchParams.categoryId" style="width: 100px;" v-model="scope.row.softNum" @keyup.enter.native="setSoft(scope.row,scope.row.softNum)">-->

<!--        </el-input>-->
      </template>
    </avue-crud>

    <upload-modal ref="uploadModalRef" @refresh-data-list="refreshChange" />
  </div>
</template>

<script setup>
import { isAuth } from '@/utils'
import { treeDataTranslate, idList } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import { tableOption } from '@/crud/prod/prodList.js'
import path from "path";
import {download} from "@/utils/http.js";
const permission = reactive({
  delBtn: isAuth('prod:prod:delete')
})
const condition=ref(false)

// function formatStatus(row, column) {
//   return " <el-switch\n" +
//     "              v-model=\"scope.row.status\"\n" +
//     "              active-value=\"0\"\n" +
//     "              inactive-value=\"1\"\n" +
//     "              @change=\"handleStatusChange(scope.row)\"\n" +
//     "          ></el-switch>"
// }
const getprodTag= ()=>{
  http({
        url: http.adornUrl('/prod/prodTag/page'),
        method: 'get',
        data: {}
      })
        .then((res) => {
          tableOption.column[7].dicData=[]
          // console.log(tableOption);
          let list=[]
          res.data.records.forEach(element => {
            list.push({
              label: element.title,
              value: element.id
            })
          });
          tableOption.column[7].dicData.push(...list)
          getListProdCategory()

        })
}
const getListProdCategory= ()=>{
  http({
        url: http.adornUrl('/prod/category/listProdCategory'),
        method: 'get',
        data: {}
      })
        .then((res) => {
          tableOption.column[8].dicData=[]
          // console.log(tableOption);
          let list=[]
          res.data.forEach(element => {
            list.push({
              label: element.categoryName,
              value: element.categoryId,

            })
          });
          res.data.forEach(element => {
            list.forEach(element2 => {
            if(element.categoryId==element2.value&&element.categories){
              element2.children=[]
              element.categories.forEach(e=>{

                element2.children.push({value:e.categoryId,label:e.categoryName})
              })
            }
          })
          })
          tableOption.column[8].dicData.push(...list)
          console.log(tableOption.column[8].dicData,777777);
          condition.value=true
        })
}
getprodTag()

const dataList = ref([])
var searchParams = {};
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const dataListLoading = ref(false)
/**
 * 获取数据列表
 */
const getDataList = async (pageParam, params, done) => {
  if(!params) params = searchParams;
  dataListLoading.value = true
  http({
    url: http.adornUrl('/prod/prod/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        params
      )
    )
  })
    .then(({ data }) => {


      dataList.value = data.records
      for (const key in dataList.value) {
        // eslint-disable-next-line no-prototype-builtins
        if (dataList.value.hasOwnProperty(key)) {
          const element = dataList.value[key]
          element.imgs = element.imgs.split(',')[0]
        }
      }
      page.total = data.total
      dataListLoading.value = false

      if (done) done()
    })
}
const router = useRouter()

const checkTop = (id) => {

  return id == 99999;
}
/**
 * 新增 / 修改
 * @param id
 */
const onTopOrUpdate = (prodId,softNum) => {


  http({
    url: http.adornUrl('/prod/prod/prodTop?prodId=' + prodId + "&softNum=" + softNum),
    method: 'put',
    data: ''
  })
    .then(() => {
      ElMessage({
        message: '操作成功',
        type: 'success',
        duration: 1500,
        onClose: () => {
          getDataList(page)
        }
      })
    })
}
/**
 * 新增 / 修改
 * @param id
 */
const onAddOrUpdate = (id) => {
  router.push({
    path: '/prodInfo',
    query: { prodId: id }
  })
}
/**
 * 删除和批量删除
 * @param id
 */
const onDelete = (id) => {
  const prodIds = getSeleProdIds()
  if (id) {
    prodIds.push(id)
  }
  ElMessageBox.confirm(`确定进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      http({
        url: http.adornUrl('/prod/prod'),
        method: 'delete',
        data: http.adornData(prodIds, false)
      })
        .then(() => {
          ElMessage({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              getDataList(page)
            }
          })
        })
    })
    .catch(() => { })
}


/**
 * 导出sku
 * @param id
 */
const handleOutSku = (id) => {
  console.log("sku_")
  let fileName = "sku_" + new Date().getTime() + ".xlsx";
  download("/prod/prod/exportSKUExcel", null, fileName);
}

/**
 * 导如sku
 * @param id
 */
const handlePUTSku = (id) => {
  console.log("sku_")
  let fileName = "sku_" + new Date().getTime() + ".xlsx";
  download("/prod/prod/importSKUExcel", null, fileName);
}
/**
 * 条件查询
 * @param params
 * @param done
 */
const onSearch = (params, done) => {
  searchParams = params;
  if(params.categoryId){
    params.categoryId=params.categoryId[1]
  }
  getDataList(page, params, done)
}

const dataListSelections = ref([])
/**
 * 多选变化
 * @param val
 */
const selectionChange = (val) => {
  dataListSelections.value = val
}
/**
 * 获取选中的商品Id列表
 */
const getSeleProdIds = () => {
  return dataListSelections.value?.map(item => {
    return item.prodId
  })
}
//已废弃
const setSoft=(e,k)=>{
  let form={
    prodId:e.prodId,
    tagId:searchParams.tagId?e.referenceId:null,

    softNum:k
  }
  http({
        url: http.adornUrl('/prod/prod/soft'),
        method: 'post',
        data: form
      })
        .then(() => {
          ElMessage({
            message: '操作成功',
            type: 'success',
            duration: 1500,
            onClose: () => {
              getDataList(page)
            }
          })
        })


}

// //上下架
// const dataForm = ref({
//   prodId: 0,
//   status: 0,
// })


// 状态开关操作
const switChange = (row) => {
  if(row.status =="1") {
    console.log("1")
    console.log(row.status)
    // putOnShellApi( row.prodId )
    const param = {}
    param.prodId = row.prodId;
    param.status = 1;
    ElMessageBox.confirm(`确定进行[${row.status == "1" ? '上架' : '下架'}] 操作?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        http({
          url: http.adornUrl('/prod/prod/prodStatus?prodId=' + param.prodId + "&prodStatus=" + param.status),
          method: 'put',
          data: ''
        })
          .then(() => {
            ElMessage({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                getDataList(page)
              }
            })
          })
      })
      .catch(() => {
      })


  }else if(row.prodId !=null &&row.prodId !="" && row.status == '0'){

      console.log("0")
      console.log(row.status)
      // putOnShellApi( row.prodId )
      const param = {}
      param.prodId =row.prodId;
      param.status =0;
      ElMessageBox.confirm(`确定进行[${row.status =="1" ? '上架' : '下架'}] 操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          http({
            url: http.adornUrl('/prod/prod/prodStatus?prodId='+param.prodId+"&prodStatus="+param.status),
            method: 'put',
            data: ''
          })
            .then(() => {
              ElMessage({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  getDataList(page)
                }
              })
            })
        })
        .catch(() => { })


    console.log(row)
  }

  // if(row.status !="1"){
  //   console.log("0")
  //   console.log(row.status)
  //   // putOnShellApi( row.prodId )
  //   const param = {}
  //   param.prodId =row.prodId;
  //   param.status =1;
  //   ElMessageBox.confirm(`确定进行[${row.status =="1" ? '上架' : '下架'}] 操作?`, '提示', {
  //     confirmButtonText: '确定',
  //     cancelButtonText: '取消',
  //     type: 'warning'
  //   })
  //     .then(() => {
  //       http({
  //         url: http.adornUrl('/prod/prod/prodStatus?prodId='+param.prodId+"&prodStatus="+param.status),
  //         method: 'put',
  //         data: ''
  //       })
  //         .then(() => {
  //           ElMessage({
  //             message: '操作成功',
  //             type: 'success',
  //             duration: 1500,
  //             onClose: () => {
  //               getDataList(page)
  //             }
  //           })
  //         })
  //     })
  //     .catch(() => { })
  // }



  console.log(row)
}

const putOnShellApi =(prodId)=> {
  const param = {}
  param.prodId =prodId;
  param.status =1;

  http({
    url: http.adornUrl('prod/prod/prodStatus'),
    method: 'put',
    data: http.adornData(prodId, 1)
  })
    .then(() => {
      ElMessage({
        message: '上架成功',
        type: 'success',
        duration: 1500,
        // onClose: () => {
        //   getDataList(page)
        // }
      })
    })


  // return request({
  //   url: http.adornUrl('/prod/prod/prodStatus'),
  //   method:  'put',
  //   data: http.adornData(param)
  // })
}
const offShellApi =(prodId)=>  {
  const param = {}
  param.prodId =prodId;
  param.status =0;
  return request({
    url: http.adornUrl('/prod/prod/prodStatus'),
    method:  'put',
    data: http.adornData(param)
  })
}



const uploadModalRef = ref(null);

const handleImport = () => {
  uploadModalRef.value?.init();
};

</script>
<style lang="scss">
.cell .el-switch .el-switch__core{border:1px solid  #155BD4}
.el-switch .el-switch__core .el-switch__action{background-color:#155BD4;}
.el-switch.is-checked .el-switch__core .el-switch__action{background-color:#FFFFFF;}
</style>
